package com.ruoyi.gateway.config.properties;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 放行白名单配置
 * 
 * @author ruoyi
 */
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "hzl.config")
@Data
@AllArgsConstructor
public class BlackProperties
{

    private List<String> blacklistUrl;

    private List<Pattern> blacklistUrlPattern = new ArrayList<>();

    @PostConstruct
    public void init()
    {
        setBlacklistUrl(blacklistUrl);
    }

    public boolean matchBlacklist(String url)
    {
        return !blacklistUrlPattern.isEmpty() && blacklistUrlPattern.stream().anyMatch(p -> p.matcher(url).find());
    }


    public void setBlacklistUrl(List<String> blacklistUrl)
    {
        this.blacklistUrl = blacklistUrl;
        this.blacklistUrlPattern.clear();
        this.blacklistUrl.forEach(url -> {
            this.blacklistUrlPattern.add(Pattern.compile(url.replaceAll("\\*\\*", "(.*?)"), Pattern.CASE_INSENSITIVE));
        });
    }


}
